<template>
  <div class="page">
    <h2>危机与自伤/自杀干预</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按姓名/风险等级/处理状态搜索" clearable style="flex:1" @clear="onClear" />

      <el-select v-model="filterRisk" placeholder="全部风险" style="width:160px">
        <el-option label="全部" :value="''" />
        <el-option label="低风险" value="low" />
        <el-option label="中风险" value="medium" />
        <el-option label="高风险" value="high" />
      </el-select>

      <el-select v-model="filterStatus" placeholder="全部状态" style="width:160px">
        <el-option label="全部" :value="''" />
        <el-option label="处理/观察中" value="active" />
        <el-option label="已转诊/送急诊" value="referred" />
        <el-option label="随访中" value="followup" />
        <el-option label="结束" value="closed" />
      </el-select>

      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">新增危机记录</el-button>
        <el-button @click="exportCSV">导出CSV</el-button>
      </div>
    </div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="姓名" width="140" />
      <el-table-column prop="age" label="年龄" width="80" />
      <el-table-column prop="riskLevel" label="风险等级" width="120">
        <template #default="{ row }">
          <el-tag :type="row.riskLevel==='high'?'danger': row.riskLevel==='medium'?'warning':'success'">{{ labelRisk[row.riskLevel] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="presenting" label="来诊主要问题" />
      <el-table-column prop="date" label="记录日期" width="140" />
      <el-table-column prop="status" label="当前处理" width="140">
        <template #default="{ row }">
          <el-tag>{{ statusMap[row.status] }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="300">
        <template #default="{ row }">
          <el-button size="small" @click="openModal(row.id)">查看/编辑</el-button>
          <el-button size="small" type="warning" @click="createSafetyPlan(row.id)" style="margin-left:8px">制定安全计划</el-button>
          <el-button size="small" type="danger" @click="urgentReferral(row.id)" style="margin-left:8px">紧急转诊</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button @click="batchSetStatus('active')">批量标为处理中</el-button>
      <el-button @click="batchSetStatus('referred')">批量转诊</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <el-dialog :title="editingId ? '危机记录详情' : '新增危机记录'" v-model="showModal" width="800px">
      <el-form :model="form" label-width="140px">
        <el-form-item label="姓名">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="年龄/性别">
          <div style="display:flex;gap:8px">
            <el-input-number v-model="form.age" :min="0" style="width:120px" />
            <el-select v-model="form.gender" style="width:120px">
              <el-option label="男" value="M" />
              <el-option label="女" value="F" />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="主诉/来诊原因">
          <el-input v-model="form.presenting" />
        </el-form-item>
        <el-form-item label="风险评估">
          <el-select v-model="form.riskLevel" style="width:160px">
            <el-option label="低风险" value="low" />
            <el-option label="中风险" value="medium" />
            <el-option label="高风险" value="high" />
          </el-select>
        </el-form-item>
        <el-form-item label="自伤/自杀具体行为">
          <el-input v-model="form.behaviors" type="textarea" rows="3" placeholder="举例：曾有自伤、曾有自杀想法/计划/实施等" />
        </el-form-item>
        <el-form-item label="有无实施计划/工具">
          <el-select v-model="form.hasPlan" style="width:160px">
            <el-option label="无" value="no" />
            <el-option label="有" value="yes" />
            <el-option label="不确定" value="unknown" />
          </el-select>
        </el-form-item>
        <el-form-item label="紧急联络人">
          <el-input v-model="form.contact" placeholder="姓名 / 关系 / 电话" />
        </el-form-item>
        <el-form-item label="处理措施/转诊">
          <el-input v-model="form.actions" type="textarea" rows="3" />
        </el-form-item>
        <el-form-item label="当前状态">
          <el-select v-model="form.status" style="width:200px">
            <el-option label="处理/观察中" value="active" />
            <el-option label="已转诊/送急诊" value="referred" />
            <el-option label="随访中" value="followup" />
            <el-option label="结束" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注/随访计划">
          <el-input v-model="form.note" type="textarea" rows="3" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const q = ref('');
const filterRisk = ref('');
const filterStatus = ref('');
const data = ref([]);
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const editingId = ref(null);
const form = reactive({ name:'', age:0, gender:'M', presenting:'', riskLevel:'low', behaviors:'', hasPlan:'no', contact:'', actions:'', status:'active', note:'' });

const labelRisk = { low:'低风险', medium:'中风险', high:'高风险' };
const statusMap = { active:'处理/观察中', referred:'已转诊/送急诊', followup:'随访中', closed:'结束' };

onMounted(()=> load());
function load(){
  data.value = [
    {id:1,name:'小强',age:16,gender:'M',presenting:'严重抑郁情绪，自杀想法',riskLevel:'high',behaviors:'曾有自杀计划，已割腕未入院',hasPlan:'yes',contact:'父亲/张三/13800000000',actions:'立即住院转诊',status:'referred',note:'急诊处理，已联系家属'},
    {id:2,name:'小芳',age:15,gender:'F',presenting:'自伤行为',riskLevel:'medium',behaviors:'自伤史',hasPlan:'no',contact:'母亲/李四/13900000000',actions:'门诊观察+心理干预',status:'followup',note:'每周随访'}
  ];
}

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(String(d.name).toLowerCase().includes(qq) || String(d.presenting).toLowerCase().includes(qq) || String(d.contact).toLowerCase().includes(qq))) return false;
    if(filterRisk.value && d.riskLevel !== filterRisk.value) return false;
    if(filterStatus.value && d.status !== filterStatus.value) return false;
    return true;
  });
});

watch(selectedRows, v=> selectedIds.value = v.map(i=>i.id));
function onSelectionChange(rows){ selectedRows.value = rows; }
function openModal(id){ editingId.value = id || null; if(id){ const it = data.value.find(x=>x.id===id); if(it) Object.assign(form, JSON.parse(JSON.stringify(it))); } else { Object.assign(form,{ name:'', age:0, gender:'M', presenting:'', riskLevel:'low', behaviors:'', hasPlan:'no', contact:'', actions:'', status:'active', note:'' }); } showModal.value = true; }
function closeModal(){ showModal.value = false; editingId.value = null; }
function save(){ if(!form.name){ ElMessage.warning('姓名为必填项'); return; } if(editingId.value){ const it = data.value.find(x=>x.id===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(form))); } else { const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; data.value.push(Object.assign({id:nid}, JSON.parse(JSON.stringify(form)))); } ElMessage.success('保存成功'); showModal.value = false; }

function createSafetyPlan(id){ const it = data.value.find(x=>x.id===id); if(!it) return; ElMessage.info('已创建安全计划草稿，可在详细页完善'); }
function urgentReferral(id){ const it = data.value.find(x=>x.id===id); if(!it) return; it.status = 'referred'; ElMessage.success('已标记为紧急转诊/送急诊'); }

function getSelectedIds(){ return selectedIds.value.slice(); }
function batchSetStatus(s){ const ids = getSelectedIds(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } data.value.forEach(d=>{ if(ids.includes(d.id)) d.status = s; }); ElMessage.success('操作完成'); }
function batchDelete(){ const ids = getSelectedIds(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条记录？`,'批量删除',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.id)); selectedIds.value=[]; selectedRows.value=[]; ElMessage.success('已删除'); })
  .catch(()=>{});
}

function exportCSV(){ const csv = [ ['id','name','age','gender','presenting','date','riskLevel','behaviors','hasPlan','contact','actions','status','note'], ...data.value.map(d=>[d.id,d.name,d.age,d.gender,d.presenting,d.date||'',d.riskLevel,d.behaviors||'',d.hasPlan||'',d.contact||'',d.actions||'',d.status||'',d.note||'']) ]; const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n'); const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='crisis_interventions.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); }

function onClear(){ }
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>